package net.lcheng.shop.Controller;

import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.model.BaseVerificationCode;
import net.lcheng.model.User;
import net.lcheng.service.BaseVerificationCodeService;
import net.lcheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import java.util.Date;

/**
 * Created by zwr on 2016/6/28 0028.
 */
@Controller
public class ForgetPasswordController {
    @Autowired
    private UserService userService;
    @Autowired
    private BaseVerificationCodeService codeService;
    /**忘记密码*/
    @RequestMapping(value = "/forget_password", method = RequestMethod.GET)
    public String Index(Model model) {

        return "forget_password";
    }
    /**
     * 修改密码，保存
     */
    @RequestMapping(value = "/forget_password", method = RequestMethod.POST)
    public String forgetPasswordPost(Model model, @RequestParam("userPwd") String userPwd, @RequestParam("number") String verifyCode,
                                     @RequestParam("userPhone") String userPhone, RedirectAttributesModelMap modelMap) {
        /**检验输入的验证码是否过期了*/
        BaseVerificationCode code = codeService.getByPhoneAndCode(userPhone, verifyCode);
        if (code != null) {
            //验证码过期,刷新修改页面
            if (new Date().after(code.getExpirationTime())) {
                modelMap.addFlashAttribute("errorType", 1);
                modelMap.addFlashAttribute("error", "验证码失效");
                return "redirect:/forget_password";
            } else {
                User user = userService.getUserByPhone(userPhone);
                //更新密码
                userService.updatePassword(user.getUserId(), ParseMD5.parseStrToMd5L32(userPwd));
            }
        } else {
            modelMap.addFlashAttribute("errorType", 3);
            modelMap.addFlashAttribute("error", "验证码错误");
            return "redirect:/forget_password";
        }
        return "redirect:/login";
    }
}
